from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.hashers import make_password, check_password
import time,os
from .. import models
from django.core.paginator import Paginator
# Create your views here.



def liebiao(request):
    # 查询库里的所有数据
    info=models.Users.objects.all().exclude(status=3)
    # 接受类型
    types = request.GET.get('type')
    # 接受关键字
    search = request.GET.get('search')
    # 判断用是否搜索内容
    if types:
        if types == 'all':
            # 根据id username phone
            # select * from myadmin_users where id like %search% or username like %search% or phone like %search%
            from django.db.models import Q
            info = models.Users.objects.filter(
                Q(id__contains=search) | Q(username__contains=search) | Q(phone__contains=search))
        elif types == 'uid':
            info = models.Users.objects.filter(id__contains=search)
        elif types == 'uname':
            info = models.Users.objects.filter(username__contains=search)
        elif types == 'uphone':
            info = models.Users.objects.filter(phone__contains=search)
    # 实例化分页对象
    p = Paginator(info, 10)
    # 一共可以分多少页
    sumpage = p.num_pages
    # 取第几页的数据
    # 接受用户的页码
    page = int(request.GET.get('p', 1))
    # 第几页的数据
    page1 = p.page(page)
    # 判断 如果用输入的页码<=3 显示前五个页码
    if page <= 3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page + 2 >= sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page - 3:page + 2]
    # 进行数据分配 通过 模板语法将数据展示到模板当中
    return render(request, 'myadmin/liebiao.html',{'info': page1, 'prange': prange, 'page': page, 'sumpage': sumpage})


#删除
def shan(request):
    uid=request.GET.get('uid')
    user=models.Users.objects.get(id=uid)
    user.status=3
    user.save()
    return redirect(reverse('admin_liebiao'))

#编辑
def gai(request):
    uid=request.GET.get('uid')
    if request.method=='GET':
        user=models.Users.objects.get(id=uid)
        return render(request,'myadmin/gai.html',{'user':user})
    elif request.method=='POST':
        info=request.POST.dict()
        uinfo=models.Users.objects.get(id=uid)
        uinfo.username=info['username']
        uinfo.phone=info['phone']
        uinfo.age=info['age']
        uinfo.sex=info['sex']
        toux=request.FILES.get('tou')
        if toux:
            os.remove('.'+uinfo.tou)
            vge=touxiang(toux)
            uinfo.tou=vge
        uinfo.save()
        return redirect(reverse('admin_liebiao'))

#重置密码
def mima(request):
    uid=request.GET.get('uid')
    user=models.Users.objects.get(id=uid)
    user.password=make_password('123456', None, 'pbkdf2_sha256')
    user.save()
    return JsonResponse({'msg':"密码重置成功"})

#修改状态
def zhuangtai(request):
    uid=request.GET.get('uid')
    status = request.GET.get('status')
    try:
        user = models.Users.objects.get(id=uid)
        user.status = int(status)
        user.save()
        msg = {'msg': '修改成功'}
        return JsonResponse(msg)
    except:
        msg = {'msg': '修改失败'}
        return JsonResponse(msg)

def zhuce(request):
    if request.method=="GET":
        return render(request,'myadmin/zhuce.html')
    elif request.method=="POST":
        user = request.POST.dict()
        user.pop('csrfmiddlewaretoken')
        mytou = request.FILES.get("tou", None)
        if not mytou:
            return HttpResponse("<script>alert('请选择头像');location.href=''</script>")
        user['tou'] = touxiang(mytou)
        user['password'] = make_password(user['password'], None, 'pbkdf2_sha256')
        try:
            user = models.Users(**user)
            user.save()
            return redirect(reverse('admin_liebiao'))
        except:
            return HttpResponse("<script>alert('添加失败！');location.href=''</script>")
#传文件
def touxiang(mytou):
    # 新名字
    newtou = str(time.time()) + "." + mytou.name.split('.').pop()
    destination = open("./static/pics/" + newtou, "wb+")
    for chunk in mytou.chunks():  # 分块写入文件
        destination.write(chunk)
    destination.close()
    return '/static/pics/' + newtou